package com.atguigu.grainmall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author shiyuan
 * @Date 2023/3/19 17:04
 * @Version 1.0
 * 远程服务调用拦截器(解决远程调用请求头丢失问题)
 **/
@Configuration
public class GrainFeignConfig {


    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 从RequestContextHolder拿到刚进来的这个请求信息
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null){
                    HttpServletRequest request = requestAttributes.getRequest();// 老请求
                    if (request != null){
                        // 同步请求头数据到新请求的Cookie
                        String cookie = request.getHeader("Cookie");
                        // 同步老请求中的cookie数据
                        requestTemplate.header("Cookie",cookie);
                    }
                }
            }
        };
    }

}
